--[[

  这个封装的太固定了，可以参考自行封装一个
------------------
  文件管理
  -- 目前主要用于存储 敦煌记录
  ---- 存储目录: /sdcard/TouchSprite/res/dh/
  ---- 文件名格式: psg-dh_年-月-日.txt
  ---- 内容格式: 1,1,1 = 今日 -> 次数,水池,神气的胖子
]]
local RxDhFile = {
  splitChar = ','
}

function RxDhFile:getData(name)
  local filePath = self:file_dirAutoCreate(name)
  local t, _list = self:file_read(filePath)
  _list = _list or RxDhFile.dhDefaultCount
  return t, _list
end

function RxDhFile:updata(name, _list)
  if _list == nil then
    RxLog('error RxDhFile:updata error error _list==nil')
    return false
  end
  RxLog('RxDhFile:updata')
  local filePath = self:file_dirAutoCreate(name)
  return self:file_write(filePath, _list)
end

function RxDhFile:file_path(name)
  name = name or '_name_'

  local ct = os.date('%Y-%m-%d', os.time()) -- 日期
  local dir = userPath() .. '/res/dh/'
  local filePath = dir .. tostring(name) ..'_'.. ct .. '.txt'
  return filePath, dir, ct
end

function RxDhFile:file_binary_path(name)
  name = name or '_unknow_'
  local dir = userPath() .. '/res/binary/'
  self:AutoCreate(dir)
  local filePath = dir .. name .. '.txt'
  local bool, kind = RxDhFile:file_exist(filePath)
  return filePath, dir, bool, kind
end

function RxDhFile:file_exist(filePath)
  if not filePath then return false end
  local bool, kind = isFileExist(filePath)
  if bool then
    if kind then
      -- 文件
      return true
    end
  end
  return false
end

function RxDhFile:file_dirAutoCreate(name)
  local filePath,dir = RxDhFile:file_path(name)
  RxDhFile:AutoCreate(dir)
  return filePath
end

function RxDhFile:AutoCreate(filePath)
  local bool, kind = isFileExist(filePath)
  function c()
    os.execute('mkdir '..filePath)
  end

  if bool then
    -- 文件或文件夹是否存在，true - 存在；false - 不存在
    if not kind then
      -- 仅 TSLib v1.2.8 及其以上版本支持，属性，true - 文件，false - 文件夹
      c()
    end
  else
    c()
  end
  return bool, kind
end


function RxDhFile:file_read(filePath)
  mSleep(1)
  RxLog('RxDhFile:file_read filePath='..tostring(filePath))
  local _list = {}
  local exist = self:file_exist(filePath)
  RxLog('RxDhFile:file_read filePath exist='..tostring(exist))
  if not exist then
    return false, _list
  end
  -- local text = readFileString(filePath)
  local text = _RxDhFile_io_read(filePath)
  RxLog('RxDhFile:file_read filePath text='..tostring(text)..'--type='..tostring(type(text)))
  if not text then
    return false, _list
  end
  local ts = require('ts')
  local cjson = ts.json
  _list = cjson.decode(text)
  return true, _list
end

function _RxDhFile_io_read(filePath)
  local f = io.open(filePath, 'r')
  local lines = f:read('*all')
  f:close()
  return lines
end

function RxDhFile:file_write(filePath, _list)
  mSleep(1)
  local ts = require('ts')
  local cjson = ts.json
  local text = cjson.encode(_list) or ''
  local bool = writeFileString(filePath, text, 'w')
  RxLog('RxDhFile:file_write bool='..tostring(bool).. ' text='..tostring(text))
  return bool
end

function RxDhFile:file_delFile(filePath)
  local kind = RxDhFile:file_exist(filePath)
  if kind then
    RxLog('del - file='..tostring(filePath))
    delFile(filePath)
  end
end

-- 获取文件名
function RxDhFile:file_stripPath(filePath)
  local filename = string.match(filePath, '.+/([^/]*%.%w+)$')
  if filename == nil then
    return filePath
  end
  return filename
end

-- 去除 文件名的 扩展名
function RxDhFile:file_stripExtension(filename)
  local idx = string.match(filename, '.+()%.%w+$')
  if idx and idx > 1 then
    return filename:sub(1, idx - 1)
  end
  return filename
end

-- 没有扩展名 的 日期文件名: /xx/xx/x_2022-06-24，返回日期字符串 -> 2022-06-24
function RxDhFile:file_dhCountOfData(filePath)
  local fnm = self:file_stripPath(filePath)
  local fileName = self:file_stripExtension(fnm)
  local fn_t = fileName
  while true do
    local idx = string.find(fn_t, '_')
    local t = string.len(fn_t)
    if idx then
      fn_t = string.sub(fn_t,idx + 1, t)
    else
      break
    end
  end
  return fn_t
end

-- 时间戳 - 相差多少天
function RxDhFile:data_subDay(a, b, day)
  day = day or 0
  a = tonumber(a)
  b = tonumber(b)
  day = tonumber(day)
  local v = 86400 * day
  if math.abs(a - b) >= v then
    return true
  end
  return false
end

-- 日期字符串: 2022-06-24, 分隔成 table[3]
function RxDhFile:file_nameData(fnm)
  local fnm_tab = UtilStringSplit(fnm,'-')
  local y,m,d = fnm_tab[1], fnm_tab[2], fnm_tab[3]
  -- RxLog('RxDhFile:file_nameData fnm='..fnm..' y='..tostring(y)..' m='..tostring(m)..' d='..tostring(d))
  return y,m,d
end

-- 日期文件路径: 返回多参结果为 -> year,month,day
function RxDhFile:file_namePathData(filePath)
  local fnm = self:file_dhCountOfData(filePath)
  local y,m,d = self:file_nameData(fnm)
  return y,m,d
end

-- 日期字符串: 2022-06-24, 返回时间戳
function RxDhFile:file_nameInterval(filePath)
  local y,m,d = self:file_nameData(filePath)
  local interval = os.time({year = y, month = m, day = d})
  return interval
end

-- 日期文件路径: xxx_2022-06-24, 返回时间戳
function RxDhFile:file_namePathInterval(filePath)
  local y,m,d = self:file_namePathData(filePath)
  local interval = os.time({year = y, month = m, day = d})
  return interval
end

-- 根据 [RxShowUI - 配置的保留天数，进行清理缓存]
function RxDhFile:file_cleanOldFile()
  local dh_saveday = UiVa.ui.dh_saveday or '3'
  local saveDay = tonumber(dh_saveday)
  local filePath, dir, ct = self:file_path()
  local currentInterval = self:file_nameInterval(ct)
  local a = io.popen('ls '..dir)
  for l in a:lines() do
    local fullPath = dir .. '/'..l
    local kind = RxDhFile:file_exist(fullPath)
    if kind then
      local old_l = self:file_namePathInterval(l)
      local v = self:data_subDay(currentInterval, old_l, saveDay)
      if v then
        local new_l = dir .. '/'.. l
        local bool = delFile(new_l)
        RxLog('file_cleanOldFile 文件删除是否成功 filePath='..tostring(new_l)..' 结果:'..tostring(bool))
      end
    end
  end
end

-- 删除敦煌脚本-产生的垃圾文件 -- 这个不会有用的，我已经改过 截图 路径了
function RxDhFile:file_cleanDhPngFile()
  local dhFileDir = userPath() .. '/res/'
  local a = io.popen('ls '..dhFileDir)
  RxLog('主目录 ='..tostring(dhFileDir))
  for l in a:lines() do
    local fullPath = dhFileDir ..l
    local kind = RxDhFile:file_exist(fullPath)
    RxLog('ex='..tostring(ex)..' kind='..tostring(kind)..'  png='..tostring(fullPath))
    if kind then
      RxLog('png='..tostring(fullPath))
      delFile(fullPath)
    end
  end
end

-- 测试代码: 创建多个文件
function RxDhFile:file_testWrite()
  local ts = require('ts')
  local testTab = RxDhFile.dhDefaultCount
  testTab.count = 2
  testTab.yubi = 555
  testTab.shenqi = 9
  local text = cjson.encode(testTab) or ''

  local num = 10
  local whileNum = 0
  local filePath, dir, ct = self:file_path()
  local y,m,d = self:file_nameData(ct)
  local filePre = userPath()..'/res/dh/psg-dh_j_'
  while true do
    whileNum = whileNum + 1
    if whileNum > num then
      break
    end
    local newPath = filePre .. tostring(y-1) .. '-' .. tostring(m) .. '-' .. tonumber(d - whileNum) .. '.txt'
    local bool = writeFileString(newPath, text, 'w')
    RxLog('RxDhFile:file_write bool=' .. tostring(bool))
  end
end

return RxDhFile